package com.njupt.Array;

/**
 * 59.螺旋矩阵II
 */
public class GenerateMatrix {

    public int[][] generateMatrix(int n) {
        int[][] nums = new int[n][n];
        int loop = 1;
        int startX = 0;
        int startY = 0;
        int i = 0;
        int j =  0;
        int offSet = 1;
        int count = 1;

        if(n==1){
            nums[0][0] = 1;
            return nums;
        }


        while(loop<=n/2){

            //遍历顶部
            for ( j = startY; j < n-offSet; j++) {
                nums[startX][j] = count++;
            }

            //遍历右侧
            for ( i = startX; i < n-offSet ; i++) {
                nums[i][j] = count++;
            }

            //遍历底部
            for ( ; j >startY ; j--) {
                nums[i][j] = count++;
            }

            for ( ; i >startX ; i--) {
                nums[i][startY] = count++;
            }
            startX++;
            startY++;
            loop++;
            offSet++;
            if(n%2 != 0){
                nums[startX][startY] =  n * n;
            }
        }

        return nums;
    }

    public static void main(String[] args) {
        GenerateMatrix test = new GenerateMatrix();
        int[][] ints = test.generateMatrix(2);
        for (int i = 0; i < ints.length; i++) {
            for (int j = 0; j < ints[0].length; j++) {
                System.out.print(ints[i][j]+ "  ");
            }
            System.out.println();
        }
    }
}
